package ca.tatham.senssim.pddd;

import ca.tatham.senssim.Packet;
import ca.tatham.senssim.Simulation;
import ca.tatham.senssim.diffusion.AbstractSinkNode;
import ca.tatham.senssim.diffusion.DataMessage;
import ca.tatham.senssim.diffusion.InterestMessage;
import ca.tatham.senssim.diffusion.InterestMessage.Interest;
import ca.tatham.senssim.util.Address;

public class SinkNodePddd extends AbstractSinkNode
{
  private static final Level SINK_LEVEL = new Level();

  private static final int HEARTBEAT_INTERVAL = SimpleNodePddd.MAX_HEARTBEAT_TIMEOUT / 3;

  private final Packet m_heartbeat;

  private final int m_dataDuration = 60 * 1000 * 5; // 5 minutes
  private final int m_dataInterval = 1 * 1000;
  private final Interest m_interest = new Interest(SENSOR_TYPE, m_dataInterval,
      m_dataDuration, REGION);

  public SinkNodePddd(Address address)
  {
    super(address);
    m_heartbeat = new HeartbeatPacket(address);
  }

  @Override
  protected void processDataMessage(DataMessage packet)
  {
    saveData(packet);
  }

  @Override
  public void tick()
  {
    super.tick();
    if (Simulation.getTime() % HEARTBEAT_INTERVAL == 0)
    {
      sendPacket(m_heartbeat);
    }
  }

  @Override
  protected void sendPeriodicInterest()
  {
    InterestMessage msg = new InterestMessage(getAddress(), Address.BROADCAST,
        m_interest);
    msg.setLevel(SINK_LEVEL);
    sendPacket(msg);
  }
}
